// created by noellynch
// Mar 5, 2008

package com.sceneworker.util.delegation;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;



public class DelegationEventBroadcaster 
{
	static	private		DelegationEventBroadcaster		mcl_this = new DelegationEventBroadcaster();
	
	private		Hashtable<String, ArrayList<DelegationEventListener>>		mcla_listeners = new Hashtable<String, ArrayList<DelegationEventListener>>();
	
	static	public	DelegationEventBroadcaster	inst()	{
		return mcl_this;
	}
	
	public	void	addEventListener(String str_eventType, DelegationEventListener cl_l)	{
		// check to see if there are any listeners already for this event
		ArrayList<DelegationEventListener>		lcla_listeners = mcla_listeners.get(str_eventType);
		
		// no other listeners
		if(lcla_listeners == null) {
			lcla_listeners = new ArrayList<DelegationEventListener>();
			mcla_listeners.put(str_eventType, lcla_listeners);
		}
		
		// check to see if there is a listener already registered for this event
		if(lcla_listeners.indexOf(cl_l) == -1) {
		    lcla_listeners.add(cl_l);
		}
	}
	
	public	void	broadcast(DelegationEvent cl_e)	{
		ArrayList<DelegationEventListener>		lcla_listeners = mcla_listeners.get(cl_e.getEventType());
		
		if(lcla_listeners == null) {
			return;
		}
		
		for(DelegationEventListener lcl_l : lcla_listeners) {
			lcl_l.handleEvent(cl_e);
		}
	}
	
	public void    removeEventListener(DelegationEventListener cl_l) {
	    Collection<ArrayList<DelegationEventListener>>         lcla_values = mcla_listeners.values();
	    
	    for(ArrayList<DelegationEventListener> lcla_l : lcla_values) {
	        lcla_l.remove(cl_l);
	    }
	}
}
